package gitbook.auth;


import gitbook.dao.UserRepository;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {

    private UserRepository userRepository;

    public MyUserDetailService(UserRepository repository){
        this.userRepository = repository;
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        gitbook.User user = userRepository.findByUserName(userName);
        if (user != null) {
//            List<GrantedAuthority> authorities = new ArrayList<>();
//            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            List<GrantedAuthority> authorities = userRepository.findAuthoritiesByUsername(userName);
            boolean userIsEnabled = userRepository.findUserIsEnabled(userName);
            return new User(user.getUsername(), user.getPassword(),userIsEnabled,
                    true,true,true,authorities);
        }
        throw new UsernameNotFoundException("用户名:" + userName + "未注册！");
    }
}
